package com.example.interview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class Utils {
    public static synchronized void getTeachers(List<Item> itemList) throws IOException, JSONException {
        URL url = new URL("https://ke.fenbi.com/api/v3/inner/teacher_promotion/?start=0&len=120");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        String response = null;
        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new
                    InputStreamReader(in, "utf-8"));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            response = stringBuilder.toString().trim();
        }
        JSONObject jsonObject = new JSONObject(response);
        JSONArray jsonArray = jsonObject.getJSONArray("datas");
        for (int i = 0; i < jsonArray.length(); ++i) {
            Item item = new Item();
            item.teacherId = jsonArray.getJSONObject(i).getInt("teacherId");
            item.brief = jsonArray.getJSONObject(i).getString("brief");
            item.desc = jsonArray.getJSONObject(i).getString("desc");
            item.image = jsonArray.getJSONObject(i).getString("image");
            item.name = jsonArray.getJSONObject(i).getString("name");
            itemList.add(item);
        }
        synchronized (itemList) {
            itemList.notify();
        }
    }

    public static synchronized void getImage(final ImageView imageView, String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            final Bitmap bitmap = BitmapFactory.decodeStream(in);
            imageView.post(() -> imageView.setImageBitmap(bitmap));
        }
    }
}
